﻿using System;
using System.Collections.Generic;
using BonsaiScrum.Bus;

namespace BonsaiScrum.Core.BusImpl
{
    public class MessageRouter : IRouteMessages
    {
        private readonly IDictionary<Type, ICollection<Action<IMessage>>> _handlers;

        public MessageRouter()
        {
            _handlers = new Dictionary<Type, ICollection<Action<IMessage>>>();
        }

        public void Route(IMessage message)
        {
            var messageType = message.GetType();
            ICollection<Action<IMessage>> handlers;

            if (!_handlers.TryGetValue(messageType, out handlers))
                throw new RouteNotRegisteredException(messageType);

            foreach (var handle in handlers)
                handle(message);
        }

        public void Register<TMessage>(Action<TMessage> handler) where TMessage : IMessage
        {
            var messageType = typeof(TMessage);
            ICollection<Action<IMessage>> handlers;

            if (!_handlers.TryGetValue(messageType, out handlers))
                _handlers[messageType] = handlers = new List<Action<IMessage>>();

            handlers.Add(message => handler((TMessage)message));
        }
    }
}
